package com.ltwc.video;

import static com.shuyu.gsyvideoplayer.utils.CommonUtil.hideNavKey;

import android.content.Context;
import android.media.MediaPlayer;
import android.util.AttributeSet;


import com.ltwc.callback.IPlayingCallback;
import com.shuyu.gsyvideoplayer.listener.GSYStateUiListener;
import com.shuyu.gsyvideoplayer.listener.GSYVideoProgressListener;
import com.shuyu.gsyvideoplayer.utils.Debuger;
import com.shuyu.gsyvideoplayer.video.base.GSYVideoView;

import java.io.File;

/**
 * Description：空白的播放器，用于电视播放，不需要任何操作的播放器
 * Created on 2024/2/02 10:38
 * Organization:华云
 * author：AHuangSHang
 **/

public abstract class BasePlayerlView extends GSYVideoView {
    //触摸显示后隐藏的时间
    protected int mDismissControlTime = 2500;

    //触摸显示虚拟按键
    protected boolean mShowVKey = false;

    //是否隐藏虚拟按键
    protected boolean mHideKey = true;

    //lazy的setup
    protected boolean mSetUpLazy = false;

    //seek touch
    protected boolean mHadSeekTouch = false;

    protected boolean mPostProgress = false;
    protected boolean mPostDismiss = false;
    protected boolean isShowDragProgressTextOnSeekBar = false;

    protected GSYStateUiListener mGsyStateUiListener;

    protected GSYVideoProgressListener mGSYVideoProgressListener;
    protected IPlayingCallback iPlayingCallback;


    public void setIPlayingCallback(IPlayingCallback iPlayingCallback) {
        this.iPlayingCallback = iPlayingCallback;
    }

    public BasePlayerlView(Context context) {
        super(context);
    }

    public BasePlayerlView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public BasePlayerlView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    protected void init(Context context) {
        super.init(context);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();

        Debuger.printfLog(BasePlayerlView.this.hashCode() + "------------------------------ dismiss onDetachedFromWindow");
        cancelProgressTimer();
        cancelDismissControlViewTimer();
    }

    @Override
    public void onAutoCompletion() {
        super.onAutoCompletion();
    }

    @Override
    public void onError(int what, int extra) {
        super.onError(what, extra);
    }

    //正常
    public static final int CURRENT_STATE_BUFFER_END = 0x99;

    /**
     * 设置播放显示状态
     *
     * @param state
     */
    @Override
    protected void setStateAndUi(int state) {
        mCurrentState = state;
        if ((state == CURRENT_STATE_NORMAL && isCurrentMediaListener())
                || state == CURRENT_STATE_AUTO_COMPLETE || state == CURRENT_STATE_ERROR) {
            mHadPrepared = false;
        }

        switch (mCurrentState) {
            case CURRENT_STATE_NORMAL:
                if (isCurrentMediaListener()) {
                    Debuger.printfLog(BasePlayerlView.this.hashCode() + "------------------------------ dismiss CURRENT_STATE_NORMAL");
                    cancelProgressTimer();
                    getGSYVideoManager().releaseMediaPlayer();
                    releasePauseCover();
                    mBufferPoint = 0;
                    mSaveChangeViewTIme = 0;
                    if (mAudioManager != null) {
                        mAudioManager.abandonAudioFocus(onAudioFocusChangeListener);
                    }
                }
                releaseNetWorkState();
                break;
            case CURRENT_STATE_PREPAREING:
                resetProgressAndTime();
                break;
            case CURRENT_STATE_PLAYING:
                if (isCurrentMediaListener()) {
                    Debuger.printfLog(BasePlayerlView.this.hashCode() + "------------------------------ CURRENT_STATE_PLAYING");
                    startProgressTimer();
                }
                break;
            case CURRENT_STATE_PAUSE:
                Debuger.printfLog(BasePlayerlView.this.hashCode() + "------------------------------ CURRENT_STATE_PAUSE");
                startProgressTimer();
                break;
            case CURRENT_STATE_ERROR:
                if (isCurrentMediaListener()) {
                    getGSYVideoManager().releaseMediaPlayer();
                }
                break;
            case CURRENT_STATE_AUTO_COMPLETE:
                Debuger.printfLog(BasePlayerlView.this.hashCode() + "------------------------------ dismiss CURRENT_STATE_AUTO_COMPLETE");
                cancelProgressTimer();
                break;
        }
        resolveUIState(state);
        if (mGsyStateUiListener != null) {
            mGsyStateUiListener.onStateChanged(state);
        }
    }


    @Override
    protected void setSmallVideoTextureView(OnTouchListener onTouchListener) {
        super.setSmallVideoTextureView(onTouchListener);

    }


    /**
     * 设置播放URL
     *
     * @param url           播放url
     * @param cacheWithPlay 是否边播边缓存
     * @param title         title
     * @return
     */
    @Override
    public boolean setUp(String url, boolean cacheWithPlay, String title) {
        return setUp(url, cacheWithPlay, (File) null, title);
    }

    /**
     * 设置播放URL
     *
     * @param url           播放url
     * @param cacheWithPlay 是否边播边缓存
     * @param cachePath     缓存路径，如果是M3U8或者HLS，请设置为false
     * @param title         title
     * @return
     */
    @Override
    public boolean setUp(String url, boolean cacheWithPlay, File cachePath, String title) {
        if (super.setUp(url, cacheWithPlay, cachePath, title)) {
            return true;
        }
        return false;
    }

    @Override
    public void onPrepared() {
        setTextAndProgress(0, true);
        super.onPrepared();
        if (mCurrentState != CURRENT_STATE_PREPAREING) return;
        startProgressTimer();

        Debuger.printfLog(BasePlayerlView.this.hashCode() + "------------------------------ surface_container onPrepared");
    }


    @Override
    public void onBufferingUpdate(final int percent) {
        post(new Runnable() {
            @Override
            public void run() {
                if (mCurrentState != CURRENT_STATE_NORMAL && mCurrentState != CURRENT_STATE_PREPAREING) {
                    if (percent != 0) {
                        setTextAndProgress(percent);
                        if (iPlayingCallback != null) {
                            iPlayingCallback.setBufferingProgress(percent);
                        }
                        mBufferPoint = percent;
                        Debuger.printfLog("Net speed: " + getNetSpeedText() + " percent " + percent);
                    }
                }
            }
        });
    }

    /**
     * 增对列表优化，在播放前的时候才进行setup
     */
    @Override
    protected void prepareVideo() {
        if (mSetUpLazy) {
            super.setUp(mOriginUrl,
                    mCache,
                    mCachePath,
                    mMapHeadData,
                    mTitle);
        }
        super.prepareVideo();
    }

    protected void showDragProgressTextOnSeekBar(boolean fromUser, int progress) {
        if (fromUser && isShowDragProgressTextOnSeekBar) {
            long duration = getDuration();
        }
    }

    /**
     * 处理控制显示
     *
     * @param state
     */
    protected void resolveUIState(int state) {
        switch (state) {
            case CURRENT_STATE_NORMAL:
                cancelDismissControlViewTimer();
                break;
            case CURRENT_STATE_PREPAREING:
                startDismissControlViewTimer();
                if (iPlayingCallback != null) {
                    iPlayingCallback.prepare();
                }
                break;
            case CURRENT_STATE_PLAYING:
                startDismissControlViewTimer();
                if (iPlayingCallback != null) {
                    iPlayingCallback.playing();
                }
                break;
            case CURRENT_STATE_PAUSE:
                cancelDismissControlViewTimer();
                if (iPlayingCallback != null) {
                    iPlayingCallback.pause();
                }
                break;
            case CURRENT_STATE_ERROR:
                if (iPlayingCallback != null) {
                    iPlayingCallback.error();
                }
                break;
            case CURRENT_STATE_AUTO_COMPLETE:
                cancelDismissControlViewTimer();
                break;
            case CURRENT_STATE_PLAYING_BUFFERING_START:
                if (iPlayingCallback != null) {
                    iPlayingCallback.playBufferingStart();
                }
                break;
            case CURRENT_STATE_BUFFER_END:
                if (iPlayingCallback != null) {
                    iPlayingCallback.playBufferingEnd();
                }
                break;
        }
    }

    protected void startProgressTimer() {
        cancelProgressTimer();
        mPostProgress = true;
        postDelayed(progressTask, 300);
    }

    protected void cancelProgressTimer() {
        mPostProgress = false;
        removeCallbacks(progressTask);
    }

    protected void setTextAndProgress(int secProgress) {
        setTextAndProgress(secProgress, false);
    }

    protected void setTextAndProgress(int secProgress, boolean forceChange) {
        long position = getCurrentPositionWhenPlaying();
        long duration = getDuration();
        long progress = position * 100 / (duration == 0 ? 1 : duration);
        setProgressAndTime(progress, secProgress, position, duration, forceChange);
    }

    protected void setProgressAndTime(long progress, long secProgress, long currentTime, long totalTime, boolean forceChange) {

        if (mGSYVideoProgressListener != null && mCurrentState == CURRENT_STATE_PLAYING) {
            mGSYVideoProgressListener.onProgress(progress, secProgress, currentTime, totalTime);
        }

        if (mHadSeekTouch) {
            return;
        }

        if (getGSYVideoManager().getBufferedPercentage() > 0) {
            secProgress = getGSYVideoManager().getBufferedPercentage();
        }
        if (secProgress > 94) secProgress = 100;
        setSecondaryProgress(secProgress);
    }

    protected void setSecondaryProgress(long secProgress) {
    }


    protected void resetProgressAndTime() {

    }

    protected void startDismissControlViewTimer() {
        cancelDismissControlViewTimer();
        mPostDismiss = true;
        postDelayed(dismissControlTask, mDismissControlTime);
    }

    protected void cancelDismissControlViewTimer() {
        mPostDismiss = false;
        removeCallbacks(dismissControlTask);
    }

    Runnable progressTask = new Runnable() {
        @Override
        public void run() {
            if (mCurrentState == CURRENT_STATE_PLAYING || mCurrentState == CURRENT_STATE_PAUSE) {
                setTextAndProgress(0);
            }
            if (mPostProgress) {
                postDelayed(this, 1000);
            }
        }
    };

    Runnable dismissControlTask = new Runnable() {
        @Override
        public void run() {
            if (mCurrentState != CURRENT_STATE_NORMAL
                    && mCurrentState != CURRENT_STATE_ERROR
                    && mCurrentState != CURRENT_STATE_AUTO_COMPLETE) {
                if (mHideKey && mIfCurrentIsFullscreen && mShowVKey) {
                    hideNavKey(mContext);
                }
                if (mPostDismiss) {
                    postDelayed(this, mDismissControlTime);
                }
            }
        }
    };

    @Override
    public void onInfo(int what, int extra) {
        if (what == MediaPlayer.MEDIA_INFO_BUFFERING_START) {
            mBackUpPlayingBufferState = mCurrentState;
            //避免在onPrepared之前就进入了buffering，导致一只loading
            if (mHadPlay && mCurrentState != CURRENT_STATE_PREPAREING && mCurrentState > 0) {
                setStateAndUi(CURRENT_STATE_PLAYING_BUFFERING_START);
            }
        } else if (what == MediaPlayer.MEDIA_INFO_BUFFERING_END) {
            if (mBackUpPlayingBufferState != -1) {
                if (mBackUpPlayingBufferState == CURRENT_STATE_PLAYING_BUFFERING_START) {
                    mBackUpPlayingBufferState = CURRENT_STATE_PLAYING;
                }
                if (mHadPlay && mCurrentState != CURRENT_STATE_PREPAREING && mCurrentState > 0) {
                    setStateAndUi(CURRENT_STATE_BUFFER_END);
                    setStateAndUi(mBackUpPlayingBufferState);
                }
                mBackUpPlayingBufferState = -1;
            }
        } else if (what == getGSYVideoManager().getRotateInfoFlag()) {
            mRotate = extra;
            Debuger.printfLog("Video Rotate Info " + extra);
            if (mTextureView != null)
                mTextureView.setRotation(mRotate);
        }

    }
}
